﻿#define  _CRT_SECURE_NO_WARNINGS
#include "Listnode.h"

LTNode* LTBuyNode(LTDataType x)
{
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror(" LTBuyNode()::fail");
		exit(-1);
	}
	node->data = x;
	node->next = node->prev = node;//自循环
	return node;
}
//初始化双链表
LTNode* LTInit()
{
	LTNode* phead = LTBuyNode(-1);
	return phead;;
}

//销毁顺序表
void LTDestroy(LTNode* phead)
{
	assert(phead && !LTEmpty(phead));
	LTNode* pcur = phead->next;
	/*while (pcur!=phead)
	{
		LTNode* next = pcur->next;
		free(pcur);
		pcur = next;
	}*/
	while (pcur != phead)
	{
		LTNode* del = pcur;
		pcur = pcur->next;
		free(del);
	}
	//头结点
	free(phead);
	phead = NULL;
}
//尾插
void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newnode = LTBuyNode(x);

	//phead phead->prev newnode
	newnode->next = phead;
	newnode->prev = phead->prev;
	phead->prev->next = newnode;
	phead->prev = newnode;
}

//打印双链表
void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

//判断双链表是否为空
bool LTEmpty(LTNode* phead)
{
	return (phead->next == phead);
}

//尾删
void LTPopBack(LTNode* phead)
{
		assert(!LTEmpty(phead));
		LTNode* del = phead->prev;
		//phead del
		del->prev->next = phead;
		phead->prev = del->prev;
		free(del);
		del = NULL;
}

//头插
void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	//phead newnode phead->next
	LTNode* newnode = LTBuyNode(x);
	newnode->next = phead->next;
	newnode->prev = phead;
	phead->prev = newnode;
	phead->next = newnode;
}

//头删
void LTPopFront(LTNode* phead)
{
	assert(!LTEmpty(phead));
	//phead del->next
	LTNode* del = phead->next;
	del->next->prev = phead;
	phead->next = del->next;
}

//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, LTDataType x) {
	assert(pos);
	//pos newnode pos->next
	LTNode* newnode = LTBuyNode(x);
	newnode->next = pos->next;
	newnode->prev = pos;
	pos->next->prev = newnode;
	pos->next = newnode;
}

//查找元素
LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(!LTEmpty(phead));
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

//删除指定位置
void LTErase(LTNode* pos)
{
	assert(pos);
	//pos->prev pos pos->next
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
	pos = NULL;
}